﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Configuration;
using DevScope.SharePoint.Utils.BulkDelete.Helpers;
using System.Xml;

namespace DevScope.SharePoint.Utils.BulkDelete.Configuration
{
    /// <summary>
    /// 
    /// </summary>
    [Serializable]
    public class Filter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Filter"/> class.
        /// </summary>
        public Filter()
        {                        
        }

        /// <summary>
        /// Gets or sets the view fields.
        /// </summary>
        /// <value>The view fields.</value>
        [XmlAnyElement("ViewFields")]
        public XmlNode ViewFields { get; set; }

        /// <summary>
        /// Gets the view fields as string.
        /// </summary>
        /// <value>The view fields as string.</value>
        public string ViewFieldsAsString
        {
            get
            {
                return (ViewFields != null ? ViewFields.InnerXml : string.Empty);
            }
        }

        /// <summary>
        /// Gets or sets the query.
        /// </summary>
        /// <value>The query.</value>
        [XmlAnyElement("Query")]
        public XmlNode Query { get; set; }

        /// <summary>
        /// Gets the query as string.
        /// </summary>
        /// <value>The query as string.</value>
        public string QueryAsString
        {
            get
            {
                return (Query != null ? Query.InnerXml : string.Empty);
            }
        }

        /// <summary>
        /// Gets or sets the query options.
        /// </summary>
        /// <value>The query options.</value>
        [XmlAnyElement("QueryOptions")]
        public XmlNode QueryOptions { get; set; }

        /// <summary>
        /// Gets the query options as string.
        /// </summary>
        /// <value>The query options as string.</value>
        public string QueryOptionsAsString
        {
            get
            {
                return (QueryOptions != null ? QueryOptions.InnerXml : string.Empty);
            }
        }

        /// <summary>
        /// Loads from file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <returns></returns>
        public static Filter LoadFromFile(string filePath)
        {
            Filter configuration;

            if (!File.Exists(filePath))
                throw new ConfigurationErrorsException(string.Format("The configuration file '{0}' must exist", filePath));

            configuration = SerializationHelper.DeserializeFromFile<Filter>(filePath);

            return configuration;
        }
    }
   
}
